package org.deyang.tools.amazon;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.deyang.tools.amazon.utils.ASINUtils;

import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;

public class TwitterPostServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1040939815366758544L;
	private static final Logger log = Logger.getLogger(TwitterPostServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String additionalHeader = req.getParameter("additionalheader");
		if (additionalHeader == null){
			additionalHeader = "";
		}
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Entity resultEntity = null;
		try {
			resultEntity = datastore.get(KeyFactory.stringToKey(req.getParameter("key")));
		} catch (EntityNotFoundException e1) {
			log.severe(e1.getMessage());
			resp.setStatus(403);
		}//pq.asSingleEntity();
		boolean postStatus = true;
		if (resultEntity != null && resultEntity.getProperty("dealPrice") != null){
			Twitter twitter = new TwitterFactory().getInstance();
			
		    try {
		    	//String saleText = (String) (resultEntity.getProperty("twitterSaleText") == null  ? "" : resultEntity.getProperty("twitterSaleText"));
		    	
		    	//Tweet has a 140 limitation for text.
		    	String productTitle = (String) resultEntity.getProperty("amazonProductTitle");
		    	if (productTitle.length() > 95){
		    		productTitle = productTitle.substring(0,91) + "..";
		    	}
		    	String urlStr = "";
				Object urlObject = resultEntity.getProperty("shorturl");
				if (urlObject instanceof Text){
					urlStr = ((Text)urlObject).getValue();
				}else{
					urlStr = (String)urlObject;
				}
				
		    	String statusString = productTitle + " " + resultEntity.getProperty("dealPrice") + " #amazon " + urlStr;
		    	if (ASINUtils.isValidISBN((String) resultEntity.getProperty("asin"))){
		    		//In case this is a book, indicate it in twitter text
		    		statusString = "#Book " + statusString;
		    	}else{
		    		statusString = additionalHeader + statusString;	
		    	}
		    	
		    	//Post to twitter system
		    	StatusUpdate su = new StatusUpdate(statusString);
		    	
				Status status = twitter.updateStatus(su);
				resp.setStatus(200);
			} catch (TwitterException e) {
				log.warning(e.getMessage());
				postStatus = false;
				resp.setStatus(400);
			}
		}else{
			log.warning("Find error when trying to twitter a product, key :" + req.getParameter("key"));
			if (resultEntity != null){
				log.warning("Asin value is : " + resultEntity.getProperty("asin"));
			}
			resp.setStatus(403);
		}
		
		try {
			Thread.sleep(120000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
//		if (postStatus){
//			resultEntity.setProperty("isPendingToTwitter", false);
//			datastore.put(resultEntity);
//		}
		
	}
}
